package org.icnmasjid.member.webapp.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.icnmasjid.member.webapp.action.BaseFormController;
import org.icnmasjid.member.model.MemberInformation;
import org.icnmasjid.member.service.Manager;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

public class MemberInformationFormController extends BaseFormController {
    public void setManager(Manager manager) {
        this.manager = manager;
    }
    public MemberInformationFormController() {
        setCommandName("memberInformation");
        setCommandClass(MemberInformation.class);
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");
        MemberInformation memberInformation = null;

        if (!StringUtils.isEmpty(id)) {
            memberInformation = (MemberInformation) manager.getObject(MemberInformation.class, new Integer(id));
        } else {
            memberInformation = new MemberInformation();
        }

        return memberInformation;
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }

        MemberInformation memberInformation = (MemberInformation) command;
        boolean isNew = (memberInformation.getId() == null);
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            manager.removeObject(MemberInformation.class, memberInformation.getId());

            saveMessage(request, getText("memberInformation.deleted", locale));
        } else {
            manager.saveObject(memberInformation);

            String key = (isNew) ? "memberInformation.added" : "memberInformation.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                return new ModelAndView("redirect:editMemberInformation.html", "id", memberInformation.getId());
            }
        }

        return new ModelAndView(getSuccessView());
    }
}
